const charset = require("superagent-charset");
const request = require("superagent");
const Promise = require("bluebird");
const cheerio = require("cheerio");
const fs = require("fs");
const cookie =
  "_ebc81c6d435065d480cb865bdbc4fec2=079bc59d76fe0bf35150d67cc342f6ab63e9a2cedb9cc95582f5a64b97b2404f20c4774c38a1f1e70fd6188df466d7ad; _ee965b7158f5ac6ba1d18e3e6bdf7644=5e46e3b2bbd243e36ea86d10cd38b144; __jsluid_s=3eecf6fb8093d74c2b0c38a082077a3b; Hm_lvt_3b387970cdb803bd81d7f67e34d57668=1698718182; font_size=; screen_width=; __guid=203173143.3999588546217064000.1698718331616.4568; count=6; Hm_lpvt_3b387970cdb803bd81d7f67e34d57668=1698739251; _0614608b11a9a44a25bfd07cf887e9a9=5ff39eddc43ec20e056e185f21a03ea4b4558ec93234287b6ee431c761ac7b0fc0f539325e4c556a0b0d0eea0d9205b8; _c26e8178126688deb863604bef4b0cda=a7eebf63d91bb807f1c8fa2c732ca9b9; _ecdcd22cb11e7f874bde71fc7a0c51d4=5f477e274059ccdb9b4b496aa0216cb5";
charset(request);
var download_path = "";
// 失败list
var fail_list = [];

// 只保留"章"字 后面的文字 第12章 徐默的报复
function getTitle(title) {
  let reg = /\d+章\s*(.*)/;
  let match = title.match(reg);
  if (match) {
    return match[1];
  } else {
    return title;
  }
}

function getPage(url) {
  return new Promise(function (resolve, reject) {
    request
      .get(url)
      //   .charset("gbk")
      .charset()
      .end(function (err, res) {
        if (err) {
          reject(err);
        } else {
          resolve(res);
        }
      });
  });
}

// 测试获取文章内容
function getContent(url) {
  return new Promise((res, rej) => {
    request
      .get(url)
      .set("Cookie", cookie)
      .charset()
      .end((err, data) => {
        if (err) {
          rej(err);
        } else {
          res(data);
        }
      });
  });
}

async function downloadPage(params) {
  let filename = `第${params.id}章—${getTitle(params.title)}.txt`;
  let path = params.path + "/" + filename;
  if (fs.existsSync(path)) {
    return;
  }
  try {
    let page = await getContent(params.href);
    let html = JSON.parse(page.text).data.content;
    fs.writeFileSync(path, html, "utf8");
  } catch (error) {
    console.log(params, "下载失败");
    fail_list.push(params);
  }
}

module.exports = {
  loader: async function (url) {
    let page = await getPage(url);
    let $ = cheerio.load(page.text);
    let title = $(".directory h1").text().trim();
    download_path = "./download/" + title;

    if (!fs.existsSync("./download")) {
      fs.mkdirSync("./download");
    }

    if (!fs.existsSync(download_path)) {
      fs.mkdirSync(download_path);
    }

    let data = [];
    $(".chapter a").each(function (i, ele) {
      let node = $(this);
      let href = `https://www.tadu.com/getPartContentByCodeTable/1005560/${
        i + 1
      }`;
      let title = node.text().trim();
      data.push({
        id: i + 1,
        href: href,
        title: title,
        path: download_path,
      });
    });

    (async function () {
      let j = 0;
      for (let i = 0; i < data.length; i++) {
        setTimeout(() => {
          const item = data[i];
          console.log(`开始下载${item.title}`);
          downloadPage(item);
          console.log(`下载${item.title}完成`);
        }, 1000 * j);
        j++;
      }
      //
    })();
  },
};
